<?php


namespace app\api\controller;


use app\BaseController;
use app\common\lib\Show;
use think\Exception;
use think\Request;
use app\api\business\User as UserBiz;

class User extends BaseController
{
    /**
     * 用户注册
     * @param Request $request
     * @return \think\response\Json
     */
    public function register(Request $request)
    {
        if (!$request->isPost()) {
            return Show::error('非法请求', 405);
        }
        $username = $request->param('username', '', 'trim');
        $password = $request->param('password', '', 'trim');
        $nickname = $request->param('nickname', '', 'trim');
        $data = [
            'username' => $username,
            'password' => $password,
            'nickname' => $nickname,
        ];
        $validate = new \app\api\validate\User();
        if (!$validate->scene('login')->check($data)){
            return Show::error($validate->getError());
        }
        // 注册有保存数据操作，会有异常发生，这里要捕获业务层抛出的异常
        try {
            $password = password_hash($password,PASSWORD_DEFAULT);
            $data['password'] = $password;
            $res = (new UserBiz())->register($data);
        }catch (Exception $e){
            return Show::error($e->getMessage(),200);
        }
        if ($res){
            return Show::success($res,'注册成功');
        }
            return Show::error('注册失败',200);

    }

    /**
     * 用户登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        if (!$request->isPost()) {
//            return Show::error('非法请求', 405);
        }
        // 接收参数
        $username = $request->param('username', '', 'trim');
        $password = $request->param('password', '', 'trim');
        $data = [
            'username' => $username,
            'password' => $password
        ];
        // 验证参数
        $validate = new \app\api\validate\User();
        if (!$validate->scene('login')->check($data)) {
            return Show::error($validate->getError());
        }
        // 登录操作
        $res = (new UserBiz())->login($data);
        if (empty($res)) {
            return Show::error('用户名或密码错误',200);
        }
        return Show::success($res, '登录成功');
    }

    /**
     * 验证登录
     * @return \think\response\Json
     */
    public function verifyLogin()
    {
        $token = $this->request->header('token');
        if (!$token){
            return Show::error('未登录！');
        }
        $res = cache(config('cache.stores.file.prefix').$token);
        if ($res){
            return Show::success($res,'success');
        }
        return Show::error('登录过期,请重新登录',200);
    }

}
